package com.atlin.nrpc.core;

import com.atlin.nrpc.core.config.RegistryConfig;
import com.atlin.nrpc.core.config.RpcConfig;
import com.atlin.nrpc.core.registry.Registry;
import com.atlin.nrpc.core.registry.RegistryFactory;
import com.atlin.nrpc.core.util.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * RPC 框架应用
 */
@Slf4j
public class RpcApplication {

    private static volatile RpcConfig rpcConfig;


    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("rpc init,config = {}", rpcConfig);

        //注册中心初始化

        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("registry init, config = {}", registryConfig);

        // 创建并注册shutdown hook, JVM退出时执行
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init() {
        RpcConfig newRpcConfig;

        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, null);
        } catch (Exception e) {
            log.error("load config error", e);
            // 使用默认值
            newRpcConfig = new RpcConfig();
        }

        init(newRpcConfig);
    }

    /**
     * 获取配置
     *
     * @return
     */
    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null)
                    init();
            }
        }
        return rpcConfig;
    }

}
